/*
 * @Description: toml 配置文件
 * @Version: 1.0
 * @Autor: JiaJun Wu
 * @Date: 2021-09-14 14:18:23
 * @LastEditors: JiaJun Wu
 * @LastEditTime: 2021-09-14 16:33:49
 */
use super::model::{caches::Caches, data_base::DataBase};
use lazy_static::*;
use rocket::serde::Deserialize;
use std::{
    env,
    fs::File,
    io::{prelude::*, Read},
};

/// 获取toml相关配置
macro_rules! get_setting_from_toml {
    ($struct:ident) => {{
        let result = $struct::default();
        let current_dir = if let Ok(v) = env::current_dir() {
            v
        } else {
            return result;
        };
        let current_path = if let Some(v) = current_dir.to_str() {
            v
        } else {
            return result;
        };
        let toml_file = format!("{}/setting.toml", current_path);
        match File::open(&toml_file) {
            Ok(mut v) => {
                let mut content = String::new();
                if let Ok(_) = v.read_to_string(&mut content) {
                    if let Ok(t) = toml::from_str::<$struct>(&content) {
                        t
                    } else {
                        result
                    }
                } else {
                    result
                }
            }
            Err(err) => {
                println!("读取文件失败: {}", err);
                result
            }
        }
    }};
}

#[derive(Debug, Deserialize, Default, Clone)]
#[serde(crate = "rocket::serde")]
pub struct Setting {
    pub secret_key: String,
    // token 有效期
    pub day_one: u64,
    // 线程数量
    pub workers: Option<u16>,
    // 数据库
    pub data_base: DataBase,
    // 缓存
    pub caches: Caches,
}

lazy_static! {
  #[derive(Deserialize,Debug,Clone,Copy)]
  #[macro_export]
  #[serde(crate = "rocket::serde")]
  pub static ref SETTING: Setting = get_setting_from_toml!(Setting);
}

/// 获取线程数
#[allow(dead_code)]
pub fn get_workers() -> u16 {
    if SETTING.workers.is_none() {
        return (num_cpus::get() * 2) as u16;
    }
    return SETTING.workers.unwrap_or(4);
}

/// 设置日志打印
#[allow(dead_code)]
pub fn init_logger() {
    use chrono::Local;

    let env = env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info");
    // 设置日志打印格式
    env_logger::Builder::from_env(env)
        .format(|buf, record| {
            writeln!(
                buf,
                "{} {} [{}] {}",
                Local::now().format("%Y-%m-%d %H:%M:%S"),
                record.level(),
                record.module_path().unwrap_or("<unnamed>"),
                &record.args()
            )
        })
        .init();
}
